package com.example.mail.controller;

import com.example.commonutils.ResultData;
import com.example.mail.utils.RandomUtil;
import com.example.servicebase.exceptionhandler.CustomException;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/mail")
public class MailAction {
    //发件人
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送邮件的方法
     *
     * @param to      发给谁
     * @return
     */
    @GetMapping(value = "send/{to}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData send(@PathVariable String to) {
        try {
            String code = redisTemplate.opsForValue().get(to);
            if (!StringUtil.isNullOrEmpty(code)){
                return ResultData.ok();
            }
            //获取4位的随机数
            code = RandomUtil.getSixBitRandom();
            String subject="在线教育平台注册验证";
            String context="您的验证码是"+code+",该验证码5分钟内有效，请勿泄露他人！";
            if (StringUtil.isNullOrEmpty(to)){
                throw new CustomException(20001,"邮件不能为空");
            }
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);//设置发件人
            message.setTo(to);//设置收件人
            message.setSubject(subject);//设置主题
            message.setText(context);//设置邮件内容
            //发送邮件
            javaMailSender.send(message);
            //保存到redis中，以便控制失效以及读取验证
            redisTemplate.opsForValue().set(to,code,5, TimeUnit.MINUTES);
            return ResultData.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(20001,"邮件发送失败");
        }
    }
}
